package com.yutian.springbootwebflux.filter;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * 若是前后端分离的vue项目，采用vue route history方式，则需要将页面请求重定向至index.html。
 * 如servlet中设置httpRequest.getRequestDispatcher("/front/index.html").forward(httpRequest, httpResponse);
 *
 * 以下假设vue build打包后的文件放在resources/static/monitor/front/index.html
 * VUE_APP_PUBLIC_PATH=/monitor/front/
 * publicPath: process.env.VUE_APP_PUBLIC_PATH
 */
@Component
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class WebFrontFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if (isStaticPage(request)) {
            return chain.filter(exchange.mutate().request(exchange.getRequest().mutate().path("/monitor/front/index.html").build()).build());
        }
        return chain.filter(exchange);
    }

    public static boolean isStaticPage(ServerHttpRequest request) {
        String uri = request.getURI().getPath();
        if (uri.startsWith("/monitor/front/")
                && !uri.endsWith(".html")
                && !uri.endsWith(".js")
                && !uri.endsWith(".css")
                && !uri.endsWith(".svg")
                && !uri.endsWith(".png")) {
            return true;
        }
        return false;
    }
}